package com.tea.controller.user;

import com.tea.constant.StatusConstant;
import com.tea.dto.DishListDTO;
import com.tea.entity.Dish;
import com.tea.entity.Store;
import com.tea.result.Result;
import com.tea.service.DishService;
import com.tea.service.StoreService;
import com.tea.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StoreService storeService;

    /**
     * 根据分类id查询菜品
     *
     * @param dishListDTO
     * @return
     */
    @PostMapping("/list")
    @ApiOperation("根据分类id和店铺id查询菜品")
    public Result<List<Dish>> list(@RequestBody DishListDTO dishListDTO) {

        //构造redis中的key，规则：dish_店铺ID_分类id
        String key = "dish_" + dishListDTO.getStoreId()+"_"+dishListDTO.getCategoryId();
        log.info("打印菜品接口被调用，所接受数据为：{}",dishListDTO);
        //查询redis中是否存在菜品数据
        List<Dish> list = (List<Dish>) redisTemplate.opsForValue().get(key);
        if(list != null && list.size() > 0){
            //如果存在，直接返回，无须查询数据库
            return Result.success(list);
        }

        Dish dish = new Dish();
        dish.setCategoryId(dishListDTO.getCategoryId());
        dish.setStoreId(dishListDTO.getStoreId());
        dish.setStatus(StatusConstant.ENABLE);//查询起售中的菜品

        //如果不存在，查询数据库，将查询到的数据放入redis中
        list = dishService.list(dishListDTO);
        redisTemplate.opsForValue().set(key, list);

        return Result.success(list);
    }


    @GetMapping("/home")
    @ApiOperation("展示所有商家")
    public Result<List<Store>> list(){
        Store store=new Store();
        List<Store> StoreList=storeService.list(store);
        return Result.success(StoreList);
    }
}
